<template>
	<div class="w-full mt-5">
		<el-row>
			<div class="w-full" style="display: flex">
				<el-checkbox v-model="props.projectInfo.selected" v-if="props.type == 1 && !props.isPrint" style="margin-right: 5px"></el-checkbox>
				<el-descriptions direction="vertical" :column="7" border class="w-full">
					<el-descriptions-item label="项目名称">
						<el-link type="primary" @click="handleProjectClick">{{ props.projectInfo.name }}</el-link>
					</el-descriptions-item>
					<el-descriptions-item label="项目编号">{{ props.projectInfo.code }}</el-descriptions-item>
					<el-descriptions-item label="项目类型">{{ props.projectInfo.typeName }}</el-descriptions-item>
					<el-descriptions-item label="合同金额（元）">{{ props.projectInfo.contractAmount?.toFixed(2) }}</el-descriptions-item>
					<el-descriptions-item label="月控制成本（元）">{{ props.projectInfo.monthLimit?.toFixed(2) }}</el-descriptions-item>
					<el-descriptions-item label="总控制成本（元）">{{ props.projectInfo.costAmount?.toFixed(2) }}</el-descriptions-item>
					<el-descriptions-item label="利润率">
						{{ props.projectInfo.profitRate ? props.projectInfo.profitRate.toFixed(2) + '%' : '' }}
					</el-descriptions-item>
				</el-descriptions>
			</div>
		</el-row>
		<el-row v-if="!isPrint" class="w-full mt-5 mb-5">
			<div class="w-full" style="text-align: right">
				月份
				<el-select v-model="queryForm.yearMonth" placeholder="请选择月份" @change="getDataList">
					<el-option :key="index" :label="item.yearMonth" :value="item.yearMonth" v-for="(item, index) in list" />
				</el-select>
			</div>
		</el-row>
		<div v-if="isPrint" class="mt-5 mb-5" style="font-size: 16px; text-align: right">
			<div>{{ queryForm.yearMonth }}</div>
		</div>
		<el-row>
			<div class="w-full">
				<div :key="row" v-for="(item, row) in titleList" style="display: flex; align-items: center">
					<div style="width: 85%; display: -webkit-box; line-height: 30px; align-items: center">
						<div style="width: 150px; text-align: left; padding-left: 15px">
							<div>{{ item.title }}</div>
							<div v-if="item.code != 'ratio'">（{{ getCellValue(totalData[item.code]) }}万元）</div>
							<div v-else>（{{ totalData[item.code] ? totalData[item.code].toFixed(2) + '%' : '-' }}）</div>
						</div>
						<div style="width: calc(100% - 150px); display: -webkit-box; text-align: center">
							<div :key="index1" v-for="(item1, index1) in list" :style="getCellWidth(item1, row, totalData)">
								<div
									v-if="row < 2 || item1.costActual"
									:class="cellClassNames(row, index1)"
									style="border: 1px solid #ebeef5; text-align: center; height: 100%"
								>
									<div v-if="item.code != 'ratio' && item.code != 'costDiff'" style="color: #333333; line-height: 30px; white-space: nowrap">
										<!-- <div>{{ item1.yearMonth }}</div> -->
										<div>{{ item1.month }}月</div>
										<div>{{ item1[item.code] ? getCellValue(item1[item.code]) : '-' }}</div>
									</div>
									<div v-else-if="item.code == 'costDiff'" style="color: #333333; line-height: 60px; white-space: nowrap">
										<div>{{ item1[item.code] ? getCellValue(item1[item.code]) : '-' }}</div>
									</div>
									<div v-else style="color: #333333; line-height: 60px; white-space: nowrap">
										<div>{{ item1[item.code].toFixed(2) + '%' }}</div>
									</div>
								</div>
							</div>
						</div>
					</div>
					<div style="width: 15%; display: flex; line-height: 60px; padding-left: 15px">
						<div style="width: 120px; text-align: left">{{ item.subTitle }}</div>
						<div style="width: calc(100% - 120px); border: 1px solid #ebeef5">
							<div
								style="color: #333333; padding-left: 10px"
								:style="getCellWidth(monthCostData, row, monthCostData)"
								:class="monthCellClassName(row)"
							>
								{{ monthCostData && monthCostData[item.code] ? monthCostData[item.code].toFixed(2) : '-' }}
							</div>
						</div>
					</div>
				</div>
			</div>
		</el-row>
		<el-row class="mt-5">
			<el-card class="relative w-full">
				<el-input v-if="!isPrint" type="textarea" rows="5" v-model="queryForm.remark" placeholder="备注" />
				<span v-else>{{ queryForm.remark }}</span>
			</el-card>
		</el-row>
	</div>
</template>

<script setup lang="ts" name="projectInfo">
import { getCostTypeData as costTypeAnalysis } from '/@/api/internal/cost/intProjectAnalysis';
import { Session } from '/@/utils/storage';

// 定义变量内容
const monthCostData = ref({});

const props = defineProps({
	type: {
		type: Number,
		default: 1,
	},
	projectInfo: {
		type: Object,
		default: ref({}),
	},
	year: {
		type: Number,
		default: null,
	},
	isPrint: {
		type: Boolean,
		default: false,
	},
});

const getLastMonth = () => {
	const now = new Date(); // 当前日期
	now.setDate(1);
	const lastMonth = new Date(now); // 复制当前日期
	lastMonth.setMonth(now.getMonth() - 1); // 设置为上一个月
	return lastMonth.toISOString().slice(0, 7);
};

// 查询参数
const queryForm = reactive({
	year: null as Number | null,
	yearMonth: getLastMonth(),
	remark: '',
	projectId: '',
});

const titleList = ref([
	{ title: '总产值(万元)', subTitle: '月产值(元)', code: 'outputValue' },
	{ title: '总控制成本(万元)', subTitle: '月控制成本(元)', code: 'costLimit' },
	{ title: '当前成本(万元)', subTitle: '当前成本(元)', code: 'costActual' },
	{ title: '超支/节约(万元)', subTitle: '超支/节约(元)', code: 'costDiff' },
	{ title: '比例', subTitle: '比例', code: 'ratio' },
]);
const list = ref([]);
const totalData = ref({});

function getSortedPositionByValue(nums: number[], targetValue: number): number {
	// 按数值排序后的数组（浅拷贝避免修改原数组）
	const sortedValues = [...nums].sort((a, b) => a - b);
	// 查找目标值的第一个出现位置
	return sortedValues.indexOf(targetValue);
}

const cellClassNames = (rowIndex: number, columnIndex: number) => {
	let costDiff = list.value[columnIndex].costDiff;
	if (rowIndex == 0) return 'green-cell';
	else if (rowIndex == 1) return 'blue-cell';
	else if (costDiff == null) return '';
	else {
		if (costDiff < 0) return 'purple-cell';
		// else if (rowIndex == 2) return 'blue-cell';
		// else return 'green-cell';
		else return 'orange-cell';
	}
};

const getCellWidth = (row: any, rowIndex: number, totalData1: any) => {
	if (!row) return;
	const maxCount = Math.max(totalData1?.outputValue, totalData1?.costLimit, totalData1?.costActual);
	if (rowIndex == 0) {
		return 'width: ' + ((row.outputValue / maxCount) * 100).toFixed(2) + '%';
	} else if (rowIndex == 1) {
		return 'width: ' + ((row.costLimit / maxCount) * 100).toFixed(2) + '%';
	} else {
		if (row.costActual && row.costActual != 0) return 'width: ' + ((row.costActual / maxCount) * 100).toFixed(2) + '%';
		else return 'display: none';
	}
};

const getCellValue = (cellValue: number) => {
	// if (cellValue) return Math.floor(cellValue / 10000);
	if (cellValue) return (cellValue / 10000).toFixed(1);
	// else if (cellValue == 0) return cellValue;
	else return '-';
};

const monthCellClassName = (rowIndex: number) => {
	if (rowIndex == 1) return 'blue-cell';
	else if (rowIndex == 2) return 'orange-cell';
	else return 'green-cell';
};

// 获取成本项分析数据
const getDataList = async () => {
	// queryForm.year = props.year;
	queryForm.projectId = props.projectInfo.id;
	costTypeAnalysis(queryForm).then((res) => {
		totalData.value = res.data.totalData;
		const datas = res.data.dataList;
		list.value = datas;
		// list.value = datas && datas.length > 12 ? datas.slice(0, 12) : datas;
		// monthCostData.value = list.value[queryForm.month - 1];
		monthCostData.value = datas.filter((a: any) => a.yearMonth == queryForm.yearMonth)[0];
	});
};
getDataList();

const router = useRouter();
const handleProjectClick = () => {
	if (props.type != 1) return;
	console.log('开始跳转页面', props.projectInfo.id);
	Session.set('projectId', props.projectInfo.id);
	router.push('/internal/cost/intProjectAnalysis/project');
	// router.push({
	// 	path: '/internal/cost/intProjectAnalysis/project',
	// 	query: { projectId: props.projectInfo.id },
	// });
};
watch(
	() => props.projectInfo,
	(val) => {
		if (val) {
			getDataList();
		}
	}
);
watch(
	() => props.year,
	(val) => {
		if (val) {
			getDataList();
		}
	}
);
</script>
<style lang="scss">
.green-cell {
	background: rgba(159, 219, 29, 1); /* 设置背景色 */
}
.blue-cell {
	background: rgb(115 155 255); /* 设置背景色 rgba(22, 93, 255, 1)*/
}
.purple-cell {
	background: rgb(167 79 250); /* 设置背景色 rgba(132, 0, 255, 1)*/
}
.orange-cell {
	background: rgba(247, 186, 30, 1); /* 设置背景色 */
}

.container {
	display: flex;
	flex-direction: column; /* 垂直排列 */
	height: 100%; /* 视窗高度，根据需要调整 */

	.item {
		flex: 1; /* 每个项目平分容器的高度 */
		display: flex;
		justify-content: center; /* 水平居中 */
		align-items: center; /* 垂直居中 */
		height: 100%;

		.left {
			padding: 0 10px;
		}

		.right {
			padding: 0 10px;
			text-align: left;
			color: #ffffff;
		}
	}
}

.el-card__body {
	height: 100%;
}

.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
	background-color: #ccc !important; /* 设置为透明或你想要的颜色 */
}
</style>
